package com.example.lotterysystem.service.impl;

import com.example.lotterysystem.common.enums.GlobalErrorCodeEnum;
import com.example.lotterysystem.common.exception.GlobalException;
import com.example.lotterysystem.service.PictureService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.util.Arrays;
import java.util.List;
import java.util.UUID;

@Service
@Slf4j
public class PictureServiceImpl implements PictureService {

    @Value("${pic.local-path}")
    private String localPath;
    private static final long MAX_FILE_SIZE = 10485760; // 10 MB
    private static final List<String> ALLOWED_EXTENSIONS = Arrays.asList(".jpg", ".jpeg", ".png", ".gif");

    @Override
    public String savePicture(MultipartFile file) {
        // 创建目录
        File newFile = new File(localPath);
        if(!newFile.exists()){
            newFile.mkdirs();
        }

        if (file.getSize() > MAX_FILE_SIZE) {
            throw new GlobalException(GlobalErrorCodeEnum.PICTURE_ERROR, "文件大小太大");
        }

        // 创建索引
        String fileName = file.getOriginalFilename();
        assert fileName != null;
        String suffix = fileName.substring(fileName.lastIndexOf(".")).toLowerCase();

        if (!ALLOWED_EXTENSIONS.contains(suffix)) {
            throw new GlobalException(GlobalErrorCodeEnum.PICTURE_ERROR, "图片格式错误");
        }
        fileName = UUID.randomUUID() + suffix;

        // 图片保存
        try {
            file.transferTo(new File(localPath + "/" + fileName));
        } catch (IOException e) {
            log.error("图片上传失败: {}", fileName, e);
            throw new GlobalException(GlobalErrorCodeEnum.PICTURE_ERROR);
        }
        return fileName;
    }
}
